"use strict";
/* Controllers */
app.controller("healthScoreList2Controller", ['$scope', '$compile', '$location', '$rootScope', '$routeParams', 'healthScoreList2Service', function ($scope, $compile, $location, $rootScope, $routeParams, healthScoreList2Service) {

    var vm = $scope.vm;
    vm.p = {}, vm.result = {};
    vm.p.tag = $routeParams.tag;
    vm.p.dt = $routeParams.dt;
    vm.p.dt2 = $routeParams.dt;
    vm.p.orgCnName = $routeParams.orgCnName;
    vm.p.ownerId = $routeParams.ownerId;

    if (typeof (vm.p.tag) == 'undefined' || vm.p.tag == 'all' || vm.p.tag == '0') {
        vm.p.tag = 'store';
    }
    if (vm.p.tag == 'task') {
        vm.p.tagContent = '计算';
    } else {
        vm.p.tagContent = '存储';
    }

    if (typeof (vm.p.orgCnName) == 'undefined' || vm.p.orgCnName == 'all' || vm.p.orgCnName == '0') {
        vm.p.orgCnName = ''
    }
    if (typeof (vm.p.ownerId) == 'undefined' || vm.p.ownerId == 'all' || vm.p.ownerId == '0' || vm.p.orgCnName == vm.p.ownerId) {
        vm.p.ownerId = ''
    }

    var datePicker = $('.date');
    datePicker.datetimepicker({
        locale: 'zh-cn',
        format: 'YYYY-MM-DD'
    });
    datePicker.on('dp.hide', function (e) {
        var currentInput = $(e.currentTarget).find('input');
        var eName = currentInput.attr('name');
        var p = $scope.vm.p;
        p[eName] = currentInput.val();
        $scope.$apply()
    });

    if (typeof (vm.p.dt) == 'undefined' || vm.p.dt == '' || vm.p.dt == '0') {
        vm.p.dt = new Date(new Date().getTime() - 2 * 86400000).format('yyyy-MM-dd');
    }

    if (typeof (vm.p.dt2) == 'undefined' || vm.p.dt2 == '' || vm.p.dt2 == '0') {
        vm.p.dt2 = new Date(new Date().getTime() - 2 * 86400000).format('yyyy-MM-dd');
    }

    var errorFn = function (result) {
        alert(result);
    };

    $scope.confirmAddWhiteList2 = function (ths, tag, appid, name, owner) {
        $(ths).attr("disabled", true);
        var btnText = $(ths).text()
        var params = {};
        if (btnText == '加入白名单') {
            params.opt = 'add';
        } else {
            params.opt = 'del';
        }
        params.tag = tag;
        params.ownerId = owner;

        if (params.tag == 'task') {
            params.typeCode = '计算白名单';
        } else {
            params.typeCode = '存储白名单';
        }
        params.typeDesc = tag;
        params.itemKey = appid;
        params.itemValue = getNowFormatDate(368);
        params.itemDesc = name;

        var procFn = function (response) {
            if (response.success && response.data) {
                if (btnText == '加入白名单') {
                    $(ths).text('取消白名单')
                    $(ths).removeClass('btn-success').addClass('btn-danger')
                } else {
                    $(ths).text('加入白名单')
                    $(ths).removeClass('btn-danger').addClass('btn-success')
                }
                $(ths).attr("disabled", false);
            } else {
                alert(response.msg);
                // $(ths).attr("disabled", false);
            }
        };
        healthScoreList2Service.setHealthScore(params, procFn, errorFn);
    }
    // $scope.ok = function () {
    //     var vm = $scope.vm;
    //     console.log("tag" + vm.p1.typeCode + 'appid' + vm.p1.typeCode + 'name' + vm.p1.typeCode + 'owner' + vm.p1.typeCode);
    //     var params = vm.p1;
    //     var procFn = function (response) {
    //         if (response.success && response.data) {
    //             alert("添加成功！")
    //         } else {
    //             alert(response.msg);
    //         }
    //     };
    //     healthScoreList2Service.setHealthScore(params, procFn, errorFn);

    //     $('#myModal').modal('hide')
    // }

    $scope.changePage = function () {
        var vm = $scope.vm;

        if (vm.p.orgCnName == '') {
            vm.p.orgCnName = '0';
        }
        if (vm.p.ownerId == '') {
            vm.p.ownerId = '0';
        }

        if (vm.p.tag == 'store') {
            vm.p.tag = 'task';
            $location.path('/star/cost/health_score_list2/task/' + vm.p.dt + '/' + vm.p.orgCnName + '/' + vm.p.ownerId);
        } else {
            vm.p.tag = 'store';
            $location.path('/star/cost/health_score_list2/store/' + vm.p.dt + '/' + vm.p.orgCnName + '/' + vm.p.ownerId);
        }
    };

    $scope.queryReport = function () {
        $scope.listHealthScoreAppid();
    };

    $scope.listHealthScoreAppid = function () {
        $("#refreshTable").addClass('disabled');
        $("#list_table").bootstrapTable('showLoading')
        var vm = $scope.vm;
        var params = vm.p;

        var procFn = function (response) {
            var data = response.data;
            $('#list_table').bootstrapTable('hideLoading');
            $("#refreshTable").removeClass('disabled');
            if (data == null) {
                return;
            }
            vm.result.data = data;
            $('#list_table').bootstrapTable('load', data);
        };
        healthScoreList2Service.listHealthScoreAppid(params, procFn, errorFn);
    };

    $scope.initializeController = function () {
        var vm = $scope.vm;

        var $resultTable = $('#list_table');
        $resultTable.bootstrapTable({
            pageList: [30, 50, 100, 300, 500, 1000], pageSize: 30
        });
        $resultTable.bootstrapTable('hideColumn', 'dataContent');
        $resultTable.bootstrapTable('hideColumn', 'tag');
        $resultTable.bootstrapTable('hideColumn', 'weight');


        $scope.listHealthScoreAppid();
    };

    $scope.initializeController();

}]);

/* Services */
app.service('healthScoreList2Service', ['ajaxService', function (ajaxService) {

    this.listHealthScoreAppid = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/healthScore/listHealthScoreAppid.do", successFunction, errorFunction);
    };

    this.setHealthScore = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/healthScore/setHealthScore.do", successFunction, errorFunction);
    };

}]);

function healthScoreListOpt2(value, row, index) {

    var btnText = '加入白名单'
    var btnClass = 'success'

    if (row.itemValue != null && typeof (row.itemValue) != 'undefined') {
        btnText = '取消白名单'
        btnClass = 'danger'
    }

    var btn1 = [
        '<div style="width:14rem"><a type="button" class="btn btn-xs btn-primary" ',
        'href="#/star/cost/health_score_detail2/', row.tag, '/', row.dt, '/', row.appId, '" target="_blank">', '详情分析',
        '</a> '
    ].join('');

    var btn2 = [
        '<a type="button" class="btn btn-xs btn-' + btnClass + '"',
        'onclick=angular.element(this).scope().confirmAddWhiteList2(this,"', row.tag, '",', row.appId, ',"', row.appName, '","', row.ownerId, '")>', btnText,
        '</a></div>'
    ].join('');

    return [
        btn1,
        btn2
    ].join('');
}

function healthScoreItemsFmt(value, row, index) {
    if (row.healthScore > 98) {
        return '-';
    }
    if (row.healthScore == 10) {
        return '生命周期未设置' + '<a href="https://dp.58corp.com/data-map/detail-page/' + row.id + '" target="_blank"> 去设置 </a>';
    } else {
        return '生命周期过长' + '<a href="https://dp.58corp.com/data-map/detail-page/' + row.id + '" target="_blank"> 去设置 </a>';
    }
}



function isPartitionFmt(value, row, index) {
    if (value == 0) {
        return "否"
    } else if (value == 1) {
        return "是"
    } else {
        return "-"
    }
}




function filesizeFmt(value, row, index) {
    return internationalNumberShortFormatterStorage(value);
}

/**
 * 数据的国际化格式化方式，三个数据用逗号分隔 如123456转换成123,456
 */
function internationalNumberFormatter(value) {
    value += '';
    var x = value.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function internationalNumberShortFormatterStorage(value) {
    if (value == null || typeof value == 'undefined') {
        return "";
    }
    value += '';
    var x = value.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    var times = 0;
    while (rgx.test(x1)) {
        times++;
        //		x1 = x1.replace(rgx, '$1');
        x1 = changeTwoDecimalFx(x1 / 1024);
    }

    switch (times) {
        case 0:
            return internationalNumberFormatter(value) + "B";
        case 1:
            return x1 + "KB";
        case 2:
            return x1 + "MB";
        case 3:
            return x1 + "GB";
        case 4:
            return x1 + "TB";
        case 5:
            return x1 + "PB";
        case 6:
            return x1 + "EB";
        case 7:
            return x1 + "ZB";
        case 8:
            return x1 + "YB";
        default:
            return internationalNumberFormatter(value);
    }
}

function changeTwoDecimalFx(x) {
    var fx = parseFloat(x);
    if (isNaN(fx)) {
        alert('function:changeTwoDecimal->parameter error');
        return false;
    }
    fx = Math.round(fx * 100) / 100;
    var s_x = fx.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
    }
    return s_x;
}



function appIdFmt(value, row, index) {
    if (value == null || value == '') {
        return "-"
    }
    return buildAppidUri(row.tag, value);
}

function buildAppidUri(tag, appid) {
    if (tag == 'store') {
        return '<a href="https://dp.58corp.com/data-map/detail-page/' + appid + '" target="_blank"> ' + appid + ' </a>';
    } else {
        return '<a href="https://dp.58corp.com/data-develop/task-list/task-detail/' + appid + '" target="_blank"> ' + appid + ' </a>';
    }
}


function appNameFmt(value, row, index) {
    if (value == null || value == '') {
        return "-"
    }
    var items = value.split('.');
    if (items.length == 2) {
        return items[1];
    }
    return value;
}


function healthReasonFmt(value, row, index) {
    if (value == null || value == '') {
        return "-"
    }
    var content = '';
    var rows = value.split(',');
    for (var i = 0; i < rows.length; ++i) {
        var items = rows[i].split(':');
        if (items.length == 3) {
            var code = items[0];
            var reason = items[1];
            var score = items[2];
            content += (reason + ':' + score + '<br/>');
        }
    }
    return content;
}


function tagFmt(value, row, index) {
    if (value == null) {
        return "-"
    }
    var content = '';
    switch (value) {
        case 'store':
            content = '存储';
            break;
        case 'task':
            content = '计算';
            break;
        default:
            content = '未知';
            break;
    }
    return content;
}

function dataContentFmt2(value, row, index) {
    if (value == null || value == '') {
        return "-"
    }
    var content = '';

    var items = value.split(',');

    if (row.tag == 'store') {
        if (items.length >= 6 && items[4] == 'recommend_lifecycle') {
            var v1 = items[5];
            content += ('推荐生命周期：' + v1 + '天<br/>');
        }

        if (items.length >= 12 && items[10] == 'max_access_span_in_100_days') {
            var v2 = items[11];
            content += ('近100天访问跨度： ' + v2 + '天<br/>');
        }
    } else if (row.tag == 'task') {
        if (items.length >= 6 && items[2] == 'relation_task_name' && items[3] != '-' && items[4] == 'relation_task_level' && items[5] != 1) {
            var v1 = items[3];
            var v2 = items[5];
            content += ('重要性等级：' + v1 + '，' + v2 + '<br/>');
        }
    }

    if (content == '') {
        return '-';
    }
    return content;
}


